import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

import 'onnx_permission_dialog.dart';

///
/// 语音识别/麦克风权限工具类
///
class OnnxPermissionTools {
  ///
  /// 麦克风权限
  ///
  static Future<bool> requestMicrophonePermission() async {
    final state = await Permission.microphone.request();
    return state == PermissionStatus.granted;
  }

  ///
  /// 语音识别权限
  ///
  static Future<bool> requestSpeechRecognitionPermission() async {
    final state = await Permission.speech.request();
    return state == PermissionStatus.granted;
  }

  /// 判断麦克风、语音识别权限是否已授权
  static Future<bool> hasMicrophone() => Permission.microphone.isGranted;
  static Future<bool> hasSpeechRecognition() => Permission.speech.isGranted;

  ///
  /// 检查权限
  ///
  static bool checkPermissions(
    BuildContext context, {
    required bool hasMicrophone,
    required bool hasSpeechRecognition,
    String appName = '应用',
  }) {
    // 权限判断 - 先检查权限，避免不必要的震动和遮罩显示
    if (!hasMicrophone) {
      OnnxPermissionDialog.showAppSettingsDialog(
        context,
        title: '麦克风服务已关闭',
        message: '您需要打开麦克风权限，才可以进行语音录制。请到设置->隐私->麦克风服务中开启$appName的麦克风',
      );
      return false;
    }
    if (!hasSpeechRecognition) {
      OnnxPermissionDialog.showAppSettingsDialog(
        context,
        title: '语音识别服务已关闭',
        message: '您需要打开语音识别权限，才可以进行语音识别转中文。请到设置->隐私->语音识别服务中开启$appName的语音识别',
      );
      return false;
    }
    return true;
  }
}
